import path from "path";
import fs from "fs";
import { Plugin } from "vite";

type PluginRet = { name: "mac-vite-plugin-builded"; }; // 简单处理报错
interface Options {
  /**
   * 默认是 favicon.ico
   */
  favicon?: string;
  /**
   * 默认是 index.html
   */
  index?: string;
  /**
   * 是否打印 copy icon 的信息
   */
  logCopyIcon?: boolean;
}
export function vitePluginBuilded(opt?: Options) {
  const config = {
    outDir: "", root: "",
    logCopyIcon: opt?.logCopyIcon ?? true,
    favicon: opt?.favicon ?? "favicon.ico",
    index: opt?.index ?? "index.html",
    icoPath: "",
    faviconData: null as null | NonSharedBuffer
  },
    ret: Plugin = {
      name: "mac-vite-plugin-builded",
      configResolved(c) {
        config.outDir = c?.build?.outDir;
        config.root = c.root;
        const ico = path.join(config.root, config.favicon);
        if (fs.existsSync(ico) && fs.statSync(ico).isFile()) {
          config.icoPath = ico;
          config.faviconData = fs.readFileSync(ico);
        }
      },
      closeBundle() {
        process.nextTick(() => {
          if (config.outDir && config.icoPath) { // 处理打包 favicon.icos
            const n = config.favicon,
              hf = path.resolve(config.outDir, config.index);
            if (fs.existsSync(hf) && fs.statSync(hf).isFile()) {
              const p = path.resolve(config.outDir, n);
              fs.copyFileSync(config.icoPath, p);
              if (config.logCopyIcon) {
                console.log("[mac-vite-plugin-builded]复制文件", config.icoPath, p);
              }
            }
          }
          if (/\bbuild\b/ig.test(`${process.argv.slice(2).join(",")}`)) {
            setTimeout(() => {
              console.log("[mac-vite-plugin-builded]已退出进程");
              process.exit(0);
            }, 1000);
          }
        });
      },
      configureServer(server) { // 处理开发时 获取favicon.ico为404
        server.middlewares.use((req, res, next) => {
          if (config.faviconData && req.url === '/favicon.ico') {
            res.setHeader('Content-Type', 'image/x-icon');
            res.end(config.faviconData);
          } else {
            next();
          }
        });
      },
    };
  return ret as PluginRet;
}
export default vitePluginBuilded;